package com.ziyueyuwen.xiniao.thirdpart.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.JsonUtil;
import com.suyeer.fastwechat.bean.fwtemplate.FwTemplateBean;
import com.suyeer.fastwechat.bean.fwtemplate.FwTemplateValueBean;
import com.suyeer.fastwechat.util.FwUtil;
import com.ziyueyuwen.xiniao.base.SpringFactory;
import com.ziyueyuwen.xiniao.bean.wx.TbWxUserInfo;
import com.ziyueyuwen.xiniao.dao.TbWxUserInfoMapper;
import com.ziyueyuwen.xiniao.thirdpart.bean.wx.WxTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ziyueyuwen.xiniao.util.ConstUtil.WX_PARAM_HEAD_IMG_URL;
import static com.ziyueyuwen.xiniao.util.ConstUtil.WX_PARAM_SUBSCRIBE_TIME;
import static com.ziyueyuwen.xiniao.util.ConstUtil.WX_PARAM_TAGID_LIST;

/**
 * @author wangwancheng 2018/12/4
 */
public class WxUtil {

    private final static Logger logger = LoggerFactory.getLogger(WxUtil.class);
    private final static TbWxUserInfoMapper TB_WX_USER_INFO_MAPPER = SpringFactory.getBean("tbWxUserInfoMapper");

    private final static String TEMPLATE_LESSON_REMIND = "rqI2PMX26yWMG8mnXu--G4TlkL6v4TNOxkamjSiLg6I";
    private final static String TEMPLATE_LESSON_REMIND_INFLATED = "1LrMeBZCI3yZnJGhgPpSlS-ZadC6fk1jzl4XRqFnCwU";
    private final static String TEMPLATE_LESSON_SIGN_IN = "_852ghut0bri0Gc1PC6MOMUYOyDSbg_APbK7-Du-0ew";
    private final static String TEMPLATE_LESSON_HOMEWORK = "RxXGfPqDBRMgbhXV1xnirHxc8n-O_oyMPvEyRwrFRH4";
    private final static String TEMPLATE_LESSON_HOMEWORK_COMMIT = "tdtIf42mLXjeDuqr7djgshktdnKzVDCrYniJR0yC8ms";
    private final static String TEMPLATE_LESSON_HOMEWORK_UN_COMMIT = "M5TY_QLOsQEfeWOmyXAyojViA9DZmbjOesDk-HFsSDs";
    private final static String TEMPLATE_LESSON_HOMEWORK_CORRECT = "ldGfdqs3sGrFfuVt7aZo_7cXT3FDvAHlCMNO4iPm1lc";
    private final static String TEMPLATE_LESSON_SUMMARIZE = "ECbf1jeDriTlIY-NCo4KQIRhcs2TCY8IOjKdCZScb3c";
    private final static String TEMPLATE_LESSON_REPORT = "JFHQEXR8JcE0MDm7nCgYuTLyJuepQmcM9zg-1a-EdKo";
    private final static String ERR_CODE = "errcode";
    private final static Integer ERR_CODE_VALUE = 0;

    /**
     * User: jun
     * Date: 2018/1/9
     * Desc: 更新微信用户数据
     */
    public static void updateWxUserInfo(String openid) throws Exception {
        JSONObject wxUserInfoObj = FwUtil.getUserInfoByOpenId(openid);
        TbWxUserInfo tbWxUserInfo = JsonUtil.changeType(wxUserInfoObj, TbWxUserInfo.class);
        tbWxUserInfo.setHeadImgUrl(wxUserInfoObj.getString(WX_PARAM_HEAD_IMG_URL));
        tbWxUserInfo.setTagidList(JsonUtil.parseArray(wxUserInfoObj.getJSONArray(WX_PARAM_TAGID_LIST), String.class));
        if (wxUserInfoObj.containsKey(WX_PARAM_SUBSCRIBE_TIME)) {
            wxUserInfoObj.put(WX_PARAM_SUBSCRIBE_TIME, wxUserInfoObj.getString(WX_PARAM_SUBSCRIBE_TIME) + "000");
            tbWxUserInfo.setSubscribeTime(wxUserInfoObj.getDate(WX_PARAM_SUBSCRIBE_TIME));
        }
        if (!TB_WX_USER_INFO_MAPPER.exit(tbWxUserInfo.getOpenid())) {
            throw new Exception("该微信用户不存在或已删除!");
        }
        if (!TB_WX_USER_INFO_MAPPER.update(tbWxUserInfo)) {
            throw new Exception("更新信息失败!");
        }
        if (!tbWxUserInfo.getSubscribe()) {
            throw new Exception("该微信用户未关注公众号, 只更新了基本信息!");
        }
    }

    public static Boolean sendTemplate(String templateId, String openId, String url, WxTemplate wxTemplate) throws Exception {
        FwTemplateBean bean = new FwTemplateBean();
        bean.setTemplate_id(templateId);
        bean.setTouser(openId);
        bean.setUrl(url);
        bean.setData(wxTemplate.getFwTemplateValueBeanHashMap());
        if (StringUtils.isBlank(openId)){
            throw new Exception("微信消息发送失败,openId为空");
        }
        JSONObject res = FwUtil.sendTemplate(bean);
        if (res.isEmpty()) {
            throw new Exception(String.format("微信消息发送失败,templateId=%s,openId=%s", templateId, openId));
        }
        Boolean ifSuccess = false;
        if (res.getIntValue(ERR_CODE) == ERR_CODE_VALUE) {
            ifSuccess = true;
        }
        return ifSuccess;
    }
    /**
     * 发送上课提醒
     * 消息模板:
     * Hi~您报名的直播马上开始啦！
     * 课程名称：5小时西班牙语入门
     * 时间：2015年12月16日18
     * 点击我去上直播课！
     *
     * @param openId
     * @param wxTemplate
     * @throws Exception
     */
    public static Boolean sendLessonRemindInflated(String openId, String url,
                                           WxTemplate wxTemplate) {
        Boolean res = false;
        try {
            res = sendTemplate(TEMPLATE_LESSON_REMIND_INFLATED, openId, url, wxTemplate);
        } catch (Exception e) {
            logger.info("发送lessonRemindInflated消息失败:");
            logger.info("openId:{}", openId);
            logger.info("url:{}", url);
            logger.info("wxTemplate:{}", JSON.toJSON(wxTemplate));
            e.printStackTrace();
        }
        return res;
    }
    /**
     * 发送上课提醒
     * 消息模板:
     * Hi~您报名的直播马上开始啦！
     * 课程名称：5小时西班牙语入门
     * 时间：2015年12月16日18
     * 点击我去上直播课！
     *
     * @param openId
     * @param wxTemplate
     * @throws Exception
     */
    public static Boolean sendLessonRemind(String openId, String url,
                                           WxTemplate wxTemplate) {
        Boolean res = false;
        try {
            res = sendTemplate(TEMPLATE_LESSON_REMIND, openId, url, wxTemplate);
        } catch (Exception e) {
            logger.info("发送lessonRemind消息失败:");
            logger.info("openId:{}", openId);
            logger.info("url:{}", url);
            logger.info("wxTemplate:{}", JSON.toJSON(wxTemplate));
            e.printStackTrace();
        }
        return res;
    }

    public static Boolean sendLessonSummarize(String openId, String url,
                                           WxTemplate wxTemplate) {
        Boolean res = false;
        try {
            res = sendTemplate(TEMPLATE_LESSON_SUMMARIZE, openId, url, wxTemplate);
        } catch (Exception e) {
            logger.info("发送sendLessonSummarize消息失败:");
            logger.info("openId:{}", openId);
            logger.info("url:{}", url);
            logger.info("wxTemplate:{}", JSON.toJSON(wxTemplate));
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 发送作业通知
     * 消息模板:
     * 您的课程有新作业了
     * 课程名称：中央美术学院2015年度城市设计
     * 作业名称：Final Draft
     * 截止日期：2016年01月07日
     * 请在截止日期之前上传作业。
     *
     * @param openId
     * @param url
     * @param wxTemplate
     * @throws Exception
     */
    public static Boolean sendLessonHomework(String openId,
                                             String url,
                                             WxTemplate wxTemplate) {

        Boolean res = false;
        try {
            res = sendTemplate(TEMPLATE_LESSON_HOMEWORK, openId, url, wxTemplate);
        } catch (Exception e) {
            logger.info("发送lessonHomework消息失败:");
            logger.info("openId:{}", openId);
            logger.info("url:{}", url);
            logger.info("wxTemplate:{}", JSON.toJSON(wxTemplate));
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 提交作业提醒
     *
     * @param openId
     * @param url
     * @param wxTemplate
     * @throws Exception
     */
    public static Boolean sendLessonHomeworkCommit(String openId,
                                                   String url,
                                                   WxTemplate wxTemplate) {
        Boolean res = false;
        try {
            res = sendTemplate(TEMPLATE_LESSON_HOMEWORK_COMMIT, openId, url, wxTemplate);
        } catch (Exception e) {
            logger.info("发送lessonHomeworkCommit消息失败:");
            logger.info("openId:{}", openId);
            logger.info("url:{}", url);
            logger.info("wxTemplate:{}", JSON.toJSON(wxTemplate));
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 推送未提交作业提醒
     *
     * @param openId
     * @param url
     * @param wxTemplate
     * @throws Exception
     */
    public static Boolean sendLessonHomeworkUnCommit(String openId,
                                                     String url,
                                                     WxTemplate wxTemplate) {
        Boolean res = false;
        try {
            res = sendTemplate(TEMPLATE_LESSON_HOMEWORK_UN_COMMIT, openId, url, wxTemplate);
        } catch (Exception e) {
            logger.info("发送lessonHomeworkUNCommit消息失败:");
            logger.info("openId:{}", openId);
            logger.info("url:{}", url);
            logger.info("wxTemplate:{}", JSON.toJSON(wxTemplate));
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 作业批改提醒
     *
     * @param openId
     * @param url
     * @param wxTemplate
     * @throws Exception
     */
    public static Boolean sendLessonHomeworkCorrect(String openId,
                                                    String url,
                                                    WxTemplate wxTemplate) {
        Boolean res = false;
        try {
            res = sendTemplate(TEMPLATE_LESSON_HOMEWORK_CORRECT, openId, url, wxTemplate);
        } catch (Exception e) {
            logger.info("发送lessonHomeworkCorrect消息失败:");
            logger.info("openId:{}", openId);
            logger.info("url:{}", url);
            logger.info("wxTemplate:{}", JSON.toJSON(wxTemplate));
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 签到提醒
     *
     * @param openId
     * @param url
     * @param wxTemplate
     * @throws Exception
     */
    public static Boolean sendLessonSignIn(String openId,
                                           String url,
                                           WxTemplate wxTemplate) {
        Boolean res = false;
        try {
            res = sendTemplate(TEMPLATE_LESSON_SIGN_IN, openId, url, wxTemplate);
        } catch (Exception e) {
            logger.info("发送lessonSignIn消息失败:");
            logger.info("openId:{}", openId);
            logger.info("url:{}", url);
            logger.info("wxTemplate:{}", JSON.toJSON(wxTemplate));
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 发送课堂报告通知
     * @param openId
     * @param url
     * @param wxTemplate
     * @return
     */
    public static Boolean sendReport(String openId,
                                           String url,
                                           WxTemplate wxTemplate) {
        Boolean res = false;
        try {
            res = sendTemplate(TEMPLATE_LESSON_REPORT, openId, url, wxTemplate);
        } catch (Exception e) {
            logger.info("发送课堂报告消息失败:");
            logger.info("openId:{}", openId);
            logger.info("url:{}", url);
            logger.info("wxTemplate:{}", JSON.toJSON(wxTemplate));
            e.printStackTrace();
        }
        return res;
    }
}
